package com.dean.pokeking.ui.pages

import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.widget.ImageButton
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.Button
import androidx.compose.material.ButtonColors
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.dean.pokeking.*
import com.dean.pokeking.R
import com.dean.pokeking.beans.NpcButton
import com.dean.pokeking.ui.MainViewModel
import com.dean.pokeking.utils.FakeDataUtil

/**
 * @ClassName EnemyChoosePage
 * @Description EnemyChoosePage
 * @Author Dean
 * @Date 2023/3/2
 * @Version 1.0
 */

@Composable
fun EnemyChoosePage(
    modifier: Modifier = Modifier,
    onClick: (enemyName: String) -> Unit = {}
) {
    val viewModel: MainViewModel = viewModel()
    val currentPlace = viewModel.mainState.collectAsState().value.currentPlace
    val npcs = viewModel.getNpcsListByPlace(currentPlace)
    LazyVerticalGrid(
        modifier = modifier.fillMaxSize(),
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(10.dp)
    ) {
        items(items = npcs, key = { it }) {
            NpcButtonCell(npcName = it) { onClick(it) }
        }
    }
}

@Composable
fun NpcButtonCell(
    npcName: String,
    onClick: () -> Unit
) {
    val img = BitmapFactory
        .decodeStream(LocalContext.current.assets.open("npcs/$npcName.png"))
        .asImageBitmap()
    Button(
        modifier = Modifier
            .height(200.dp)
            .padding(10.dp),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Gray.copy(alpha = 0.2f)
        ),
        onClick = onClick
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(bitmap = img, contentDescription = "")
            Text(text = npcName, fontSize = 20.sp)
        }
    }
}

@Preview(showBackground = true)
@Composable
fun EnemyChoosePagePreview() {
    EnemyChoosePage()
}